#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion

#region Using directives

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using ZO.SmartCore.Helpers;
using ZO.SmartCore.Plugins;
using ZO.SmartCore.Windows.Forms;
using ZO.SmartMessenger.Plugins;

#endregion

namespace ZO.SmartMessenger.UI
{
    /// <summary>
    /// Manage Accounts
    /// </summary>
    public partial class AccountManager : Form
    {
        private const string MODIFY_DELETE_TITLE = "{0} an existing account";
        private const string MODIFY_DELETE_DESC = "Choose the account you want to {0}. Remember you can only {0} the account not currently in use.";
        /// <summary>
        /// Initializes a new instance of the <see cref="AccountManager"/> class.
        /// </summary>
        public AccountManager()
        {
            InitializeComponent();

            editMode = WizardMode.Add;
            IntroWizardPage.NextPage = AddOrEditWizardPage;
            AddOrEditWizardPage.PreviousPage = IntroWizardPage;
            AddOrEditWizardPage.NextPage = null;


            this.AccountWizard.Cancel += new EventHandler<SmartWizardEventArgs>(AccountWizard_Cancel);
        }

        /// <summary>
        /// Handles the Cancel event of the AccountWizard control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:SmartCore.Windows.Forms.SmartWizardEventArgs"/> instance containing the event data.</param>
        private void AccountWizard_Cancel(object sender, SmartWizardEventArgs e)
        {

            DialogResult dialog = MessageBox.Show(this, "Are you really want to Cancel", "Cancel Changes", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

            if (dialog == DialogResult.Cancel)
            {
                e.Cancel = true;
            }

        }

        private enum WizardMode
        {
            Add, Modify, Delete
        }

        private WizardMode editMode = WizardMode.Add;


        /// <summary>
        /// Handles the Load event of the IntroWizardPage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void IntroWizardPage_Load(object sender, EventArgs e)
        {

            DeleteRadioButton.Enabled = ModifyRadioButton.Enabled =
                MessengerHelper.Accounts.Count == 0 ? false : true;

        }

        /// <summary>
        /// Handles the Load event of the AddWizardPage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void AddOrEditWizardPage_Load(object sender, EventArgs e)
        {

            if (editMode == WizardMode.Add)
            {
                if (MessengerHelper.ProtocolPlugins.Count == 0)
                {
                    ProtocolComboBox.Enabled = false;
                    UserNameTextBox.Enabled = false;
                    PasswordTextBox.Enabled = false;
                    RememberPasswordCheckBox.Enabled = false;
                    AutoLoginCheckBox.Enabled = false;


                }
                else
                {
                    Dictionary<string, Guid> tags = new Dictionary<string, Guid>();
                    for (int i = 0; i < MessengerHelper.ProtocolPlugins.Count; i++)
                    {
                        ProtocolPlugin var = MessengerHelper.ProtocolPlugins[i];

                        tags.Add(var.Name, var.ID);
                        ProtocolComboBox.Items.Add(var.Name);
                    }

                    ProtocolComboBox.Tag = tags;

                    if (ProtocolComboBox.Items.Count > 0)
                    {
                        ProtocolComboBox.SelectedIndex = 0;
                    }
                    UserNameTextBox.Text = "";
                    PasswordTextBox.Text = "";
                    AccountNameTextBox.Text = "";

                    RememberPasswordCheckBox.Checked = true;

                    AutoLoginCheckBox.Checked = false;
                    AccountNameTextBox.Enabled = true;

                }
            }
            else if (editMode == WizardMode.Modify)
            {
                if (AccountListView.SelectedItems.Count > 0)
                {
                    ListViewItem item = AccountListView.SelectedItems[0];

                    if (MessengerHelper.Accounts.Contains(item.Text))
                    {
                        Account account = MessengerHelper.Accounts[item.Text];

                        int selectedIndex = 0;
                        Dictionary<string, Guid> tags = new Dictionary<string, Guid>();
                        for (int i = 0; i < MessengerHelper.ProtocolPlugins.Count; i++)
                        {
                            ProtocolPlugin var = MessengerHelper.ProtocolPlugins[i];

                            tags.Add(var.Name, var.ID);
                            ProtocolComboBox.Items.Add(var.Name);

                            if (var == account.Protocol)
                            {
                                selectedIndex = i;
                            }
                        }

                        ProtocolComboBox.Tag = tags;

                        ProtocolComboBox.SelectedIndex = selectedIndex;

                        UserNameTextBox.Text = account.UserName;
                        PasswordTextBox.Text = account.Password;
                        AccountNameTextBox.Text = account.AccountName;

                        RememberPasswordCheckBox.Checked = account.RememberPassword;

                        AutoLoginCheckBox.Checked = account.AutoLogin;

                        AccountNameTextBox.Enabled = false;
                    }

                    if (MessengerHelper.ProtocolPlugins.Count == 0)
                    {
                        ProtocolComboBox.Enabled = false;
                        UserNameTextBox.Enabled = false;
                        PasswordTextBox.Enabled = false;
                        RememberPasswordCheckBox.Enabled = false;
                        AutoLoginCheckBox.Enabled = false;


                    }

                }

            }

        }

        /// <summary>
        /// Handles the CheckedChanged event of the RememberPasswordCheckBox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ValidateAddWizardPage(object sender, EventArgs e)
        {
            if (sender == RememberPasswordCheckBox)
            {
                PasswordTextBox.Text = "";

                if (RememberPasswordCheckBox.Checked)
                {
                    PasswordTextBox.Enabled = true;
                    AutoLoginCheckBox.Enabled = true;
                }
                else
                {
                    PasswordTextBox.Enabled = false;
                    AutoLoginCheckBox.Enabled = false;
                }
            }

            if (ProtocolComboBox.SelectedIndex >= 0)
            {
                if (!String.IsNullOrEmpty(AccountNameTextBox.Text))
                {
                    if (!String.IsNullOrEmpty(UserNameTextBox.Text))
                    {
                        if (RememberPasswordCheckBox.Enabled && RememberPasswordCheckBox.Checked)
                        {
                            if (!String.IsNullOrEmpty(PasswordTextBox.Text))
                            {
                                AddOrEditWizardPage.AllowMoveNext = true;
                                return;
                            }
                        }
                        else
                        {
                            AddOrEditWizardPage.AllowMoveNext = true;
                            return;
                        }
                    }
                }
            }

            AddOrEditWizardPage.AllowMoveNext = false;

        }

        /// <summary>
        /// Handles the Finish event of the AccountWizard control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void AccountWizard_Finish(object sender, SmartWizardEventArgs e)
        {
            if (e.Page == AddOrEditWizardPage)
            {
                if (editMode == WizardMode.Add)
                {

                    Account account1 = new Account();

                    account1.AccountName = AccountNameTextBox.Text.Trim();

                    account1.AutoLogin = AutoLoginCheckBox.Checked;
                    account1.RememberPassword = RememberPasswordCheckBox.Checked;

                    if (PasswordTextBox.Enabled)
                    {
                        account1.Password = PasswordTextBox.Text.Trim();
                    }

                    Dictionary<string, Guid> tags = ProtocolComboBox.Tag as Dictionary<string, Guid>;

                    ProtocolPlugin var = null;

                    if (tags != null)
                    {
                        if (tags.ContainsKey(ProtocolComboBox.Text.Trim()))
                        {
                            var = MessengerHelper.ProtocolPlugins[tags[ProtocolComboBox.Text.Trim()]];
                        }
                    }

                    if (var == null)
                    {
                        e.Cancel = true;

                        return;
                    }

                    account1.Protocol = var;


                    account1.UserName = UserNameTextBox.Text.Trim();

                    MessengerHelper.Accounts.Add(account1);

                }

                if (editMode == WizardMode.Modify)
                {
                    Account account1 = null;

                    if (MessengerHelper.Accounts.Contains(AccountNameTextBox.Text.Trim()))
                    {
                        account1 = MessengerHelper.Accounts[AccountNameTextBox.Text.Trim()];
                    }

                    if (account1 == null)
                    {
                        e.Cancel = true;
                        return;
                    }

                    account1.AccountName = AccountNameTextBox.Text;

                    account1.AutoLogin = AutoLoginCheckBox.Checked;
                    account1.RememberPassword = RememberPasswordCheckBox.Checked;

                    if (PasswordTextBox.Enabled)
                    {
                        account1.Password = PasswordTextBox.Text.Trim();
                    }

                    Dictionary<string, Guid> tags = ProtocolComboBox.Tag as Dictionary<string, Guid>;

                    ProtocolPlugin var = null;

                    if (tags != null)
                    {
                        if (tags.ContainsKey(ProtocolComboBox.Text))
                        {
                            var = MessengerHelper.ProtocolPlugins[tags[ProtocolComboBox.Text]];
                        }
                    }

                    if (var == null)
                    {
                        e.Cancel = true;

                        return;
                    }

                    account1.Protocol = var;


                    account1.UserName = UserNameTextBox.Text;

                }

                DialogResult dialog = MessageBox.Show(this, "Are You want to save your changes", "Save Changes", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);

                if (dialog == DialogResult.OK)
                {
                    MessengerHelper.Accounts.Save();
                }
            }

            if (e.Page == ModifyOrDeleteWizardPage)
            {
                if (editMode == WizardMode.Delete)
                {

                    if (AccountListView.CheckedItems.Count > 0)
                    {

                        DialogResult dialog = MessageBox.Show(this, "Are You want to really want to continue", "Remove Account", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

                        if (dialog == DialogResult.Cancel)
                        {
                            e.Cancel = true;
                            return;
                        }

                        foreach (ListViewItem item in AccountListView.CheckedItems)
                        {
                            if (MessengerHelper.Accounts.Contains(item.Text))
                            {
                                MessengerHelper.Accounts.Remove(item.Text, true);

                            }
                        }

                     
                    }



                }

            }


        }

        /// <summary>
        /// Handles the CheckedChanged event of the RadioButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ChoiceRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            if (AddRadioButton.Checked)
            {
                editMode = WizardMode.Add;
                IntroWizardPage.NextPage = AddOrEditWizardPage;
                AddOrEditWizardPage.PreviousPage = IntroWizardPage;
                AddOrEditWizardPage.NextPage = null;
            }
            else if (ModifyRadioButton.Checked)
            {
                editMode = WizardMode.Modify;
                IntroWizardPage.NextPage = ModifyOrDeleteWizardPage;
                ModifyOrDeleteWizardPage.PreviousPage = IntroWizardPage;
                ModifyOrDeleteWizardPage.NextPage = AddOrEditWizardPage;
                AddOrEditWizardPage.NextPage = null;
                ModifyOrDeleteWizardPage.AllowMoveNext = false;
            }
            else if (DeleteRadioButton.Checked)
            {
                editMode = WizardMode.Delete;
                IntroWizardPage.NextPage = ModifyOrDeleteWizardPage;
                ModifyOrDeleteWizardPage.PreviousPage = IntroWizardPage;
                ModifyOrDeleteWizardPage.NextPage = null;
                ModifyOrDeleteWizardPage.AllowMoveNext = false;
            }

        }

        /// <summary>
        /// Handles the Load event of the ModifyWizardPage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void ModifyOrDeleteWizardPage_Load(object sender, EventArgs e)
        {
            AccountListView.Items.Clear();

            if (editMode == WizardMode.Modify)
            {
                AccountListView.CheckBoxes = false;
                ModifyOrDeleteHeader.Title = StringHelper.Format(MODIFY_DELETE_TITLE, "Modify");
                ModifyOrDeleteHeader.Description = StringHelper.Format(MODIFY_DELETE_DESC, "modify");
            }
            else
            {
                AccountListView.CheckBoxes = true;
                ModifyOrDeleteHeader.Title = StringHelper.Format(MODIFY_DELETE_TITLE, "Delete");
                ModifyOrDeleteHeader.Description = StringHelper.Format(MODIFY_DELETE_DESC, "delete");
            }


            for (int i = 0; i < MessengerHelper.Accounts.Count; i++)
            {
                Account account = MessengerHelper.Accounts[i];

                if (account.Login)
                {
                    continue;
                }

                PluginImage pluginImage = account.Protocol.Image;

                if (pluginImage == null)
                    continue;

                Image image = Image.FromStream(new MemoryStream(pluginImage.GetBytes()));

                ListViewItem item = new ListViewItem(account.AccountName);

                if (image != null)
                {
                    LargeImageList.Images.Add(account.AccountName, image);

                    item.ImageIndex = LargeImageList.Images.IndexOfKey(account.AccountName);
                }

                if (account.Login)
                {
                    
                }
                AccountListView.Items.Add(item);
                //ModifyLargeImageList.Images.Add()
            }
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the AccountListView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
        private void AccountListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (editMode == WizardMode.Modify)
            {
                ModifyOrDeleteWizardPage.AllowMoveNext = AccountListView.SelectedItems.Count == 0 ? false : true;
            }
            else if (editMode == WizardMode.Delete)
            {
                if (AccountListView.SelectedItems.Count > 0)
                {
                    AccountListView.SelectedItems[0].Checked = !AccountListView.SelectedItems[0].Checked;
                }
            }
            else
            {
                ModifyOrDeleteWizardPage.AllowMoveNext = false;
            }


        }







        /// <summary>
        /// Handles the ItemChecked event of the AccountListView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="T:System.Windows.Forms.ItemCheckedEventArgs"/> instance containing the event data.</param>
        private void AccountListView_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (editMode == WizardMode.Delete)
            {
                ModifyOrDeleteWizardPage.AllowMoveNext = AccountListView.CheckedItems.Count == 0 ? false : true;
            }
            else
            {
                ModifyOrDeleteWizardPage.AllowMoveNext = false;
            }
        }



    } // class Form1
}